<template>
  <div id="wrapper" v-loading="loading">
    <!--    <img id="logo" src="~@/assets/logo.png" alt="electron-vue">-->
    <el-row :gutter="0">
      <el-col :span="22">
        <input style="display: none"/>
        <el-input
            v-model="url" @keydown.enter.native="go" size="mini">
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button size="mini" type="success" plain style="width: calc(100% - 16px);margin-left: 16px;
    border: 2px solid #55c500;box-sizing: border-box;
    height: 28px;
    border-radius: 0px;" @click="go">跳 转
        </el-button>
      </el-col>
    </el-row>
    <main>
      <div class="left-side">
        <!--        <span class="title">-->
        <!--          Welcome to your new project!-->
        <!--        </span>-->
        <!--        <system-information></system-information>-->
        <webview
            ref="webViews"
            allowpopups
            style="display:flex; width:100%; height:100%;
    border: 2px solid #55c500;padding:1px"
            id="wb"
            :src="realUrl"
            autosize="on"
            webpreferences="allowRunningInsecureContent=yes"
            enableremotemodule="true"
            :preload='preload' partition="persist:qdjxjy"/>


      </div>

      <div class="right-side">

        <el-tabs v-model="activeName" type="border-card"  :before-leave='leaveTab'>
          <el-tab-pane label="挂机" name="onHook" v-if="false">
            <el-button type="success" @click="onhookAction" style="width:100%;font-size: 18px">登录后点击自动开始</el-button>
            <el-table ref="onHookTable" size="mini"
                      height="80%"
                      :data="courseListLearn"
                      row-key="courseId"
                      style="width: 100%;margin-top: 16px;" :row-style="{backgroundColor:'#eff3fd'}"
                      :header-row-style="{backgroundColor:'#eff3fd'}"
                      :cell-class-name="courseRowClass"
            >

              <el-table-column type="expand">
                <template slot-scope="props">

                  <el-table size="mini"
                            :data="props.row.children"
                            row-key="id"
                            :cell-class-name="chapterRowClass"
                  >

                    <el-table-column
                        prop="name"
                        label="章节名称">
                    </el-table-column>
                    <el-table-column
                        prop="learningStatus"
                        label="状态">
                      <template slot-scope="scope">
                        <span v-if="scope.row.learningStatus==1">待学习</span>
                        <span v-if="scope.row.learningStatus==2">学习中</span>
                        <span v-if="scope.row.learningStatus==3">完成</span>
                      </template>
                    </el-table-column>

                  </el-table>
                </template>
              </el-table-column>


              <el-table-column
                  prop="name"
                  label="课程名称">
              </el-table-column>
              <el-table-column
                  prop="status"
                  label="状态" width="60">
                <template slot-scope="scope">
                  <span v-if="scope.row.status==1">学习中</span>
                  <span v-if="scope.row.status==0">待学习</span>
                  <span v-if="scope.row.status==2">在学习</span>
                  <span v-if="scope.row.status==4">完成考试</span>
                </template>

              </el-table-column>
              <el-table-column
                  prop="answer"
                  label="类型" width="100">

                <template slot-scope="scope">
                  <span v-if="scope.row.courseType==1">专业课程</span>
                  <span v-if="scope.row.courseType==99">公需课</span>
                </template>


              </el-table-column>
              <!--              <el-table-column-->
              <!--                  prop="id"-->
              <!--                  label="id" width="50">-->
              <!--              </el-table-column>-->
            </el-table>

          </el-tab-pane>
          <el-tab-pane label="考试" name="exam">
            <el-button type="success" @click="findanswer" style="width:100%;font-size: 18px">进入考试页面后查找答案</el-button>
            <el-button type="success" @click="findanswer2" style="width:100%;font-size: 18px">2222222222</el-button>
            <el-button type="success" @click="findanswer3" style="width:100%;font-size: 18px">333333333333</el-button>
            <el-table size="mini"
                      :data="answer"
                      style="width: 100%;margin-top: 16px;"
                      :default-sort="{prop: '_index', order: 'ascending'}"
            >
              <el-table-column
                  prop="_index"
                  label="序号" width="50">
              </el-table-column>
              <el-table-column
                  prop="question"
                  label="问题">
              </el-table-column>
              <el-table-column
                  prop="answer"
                  label="答案" width="100">
              </el-table-column>
              <!--              <el-table-column-->
              <!--                  prop="id"-->
              <!--                  label="id" width="50">-->
              <!--              </el-table-column>-->
            </el-table>
          </el-tab-pane>
        </el-tabs>


      </div>
    </main>

  </div>
</template>

<script>

import { httpAction } from '@/utils/manage'

import { deleteChapter, insert, queryALl } from '@/utils/db'
import { remote } from 'electron'
export default {
  name: 'exam',

  data() {
    return {
      idlist:[],
      allinfo:[],
      info_index:undefined,
      url: 'http://192.168.11.121:12345/wui/index.html?#/main/workflow/listMine?menuIds=1,14&menuPathIds=1,14&_key=35rav1',
      realUrl: 'http://192.168.11.121:12345/wui/index.html?#/main/workflow/listMine?menuIds=1,14&menuPathIds=1,14&_key=35rav1',
      preload: undefined,
      webViews: null,
      sessionStorage: null,
      token: null,
      userid: null,
      eid: null,
      eUrlIndex: 'https://www.qdjxjy.com.cn/exam/formal?id=',
      allIds: null,
      /***
       * [{id:777,answer:'A'}]
       */
      answer: [],
      loading: false,
      activeName: 'exam',
      /***
       * 课程
       */
      courseList: [],

      /****
       * 需要学习的课程
       */
      courseListLearn: [],


      /***
       * 章节
       */
      chaptersTemp: [],


      coursePointer: null,
      chapterPointer: null,

      /**
       * 所有正在学习的课程列表
       */
      learnLog: [],





      /***
       * 存 有效的课程 数量 {2:2,3:1}
       * key是课程id
       */
      validChildrenLength: {},

      /***
       * 其他端 正在学习的{2:[2,3]}
       * key是课程id ,值是章程ID
       */
      learning: {}
    }
  },
  // computed: {
  //   importExcelUrl: function () {
  //     return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
  //   }
  // },
  // watch: {
  //   value(val) {
  //     this.userIds = val
  //   }
  // },
  beforeDestroy() {
  },
  created() {
    window.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
    this.preload = `file:${require('path').resolve(__static, './js/preload.js')}`


    this.loading=true;
  },
  mounted() {
    this.initWebViewEventListener()

  },
  methods: {
    leaveTab(activeName, oldActiveName) {
      console.log(activeName, oldActiveName);
      if(oldActiveName=='onHook'&&activeName=='exam'){
        this.webViews.executeJavaScript(`
        paused:document.querySelector('video')==null?true:document.querySelector('video').paused
    `).then((paused) => {
          if(!paused){
            this.$alert('视频正在学习中，请谨慎操作', '提示', {
              confirmButtonText: '确定',
              callback: action => {

              }
            });
          }
        });


      }
    },
    courseRowClass({row, column, rowIndex, columnIndex}){
      if(this.coursePointer&&this.coursePointer.courseId==row.courseId){
        return "learning-cell"
      }
      return ;
    },
    chapterRowClass({row, column, rowIndex, columnIndex}){
      if(this.chapterPointer&&this.chapterPointer.id==row.id){
        return "learning-cell"
      }
      return;
    },

    allinfoPush(text){
      if(this.allinfo.find((o)=>{return o==text})==undefined){
        this.allinfo.push(text);
      }
    },
    initWebViewEventListener() {


      this.webViews = this.$refs.webViews
      if (!this.webViews) return

      this.webViews.addEventListener('dom-ready', () => {
        console.log('主页面 dom 加载完成')
        // https://www.electronjs.org/zh/docs/latest/api/webview-tag#webviewgeturl
        let isLoading = this.webViews.isLoading() // 是否加载完成
        let getURL = this.webViews.getURL() // 访客页面URL
        let getTitle = this.webViews.getTitle() // 访客页面标题
        console.log(getTitle)
        this.url = getURL






        // this.webViews.stop() // 停止
        // this.webViews.reload() // 刷新   this.webViews.reloadIgnoringCache //刷新并忽略缓存
        // this.webViews.canGoBack() // 能否后退
        // this.webViews.canGoForward() // 能否前进  canGoToOffset(6) // 能否前进到
        //  this.webViews.clearHistory() // 清楚历史记录
        // this.webViews.openDevTools()
        // 给webview传值代表是桌面端使用
        this.webViews.send('smdh-electron', 'smdh-desktop')
      })


      this.webViews.addEventListener('did-start-loading', () => {
        // console.log('页面开始加载')

        let isDevelopment = process.env.NODE_ENV !== 'production'

        if (isDevelopment) {
          this.webViews.closeDevTools()
        }


        if (this.realUrl.startsWith('https://www.qdjxjy.com.cn/course/study?')) {



          let cs = this.realUrl.split('?')[1]                //获取?之后的参数字符串

          let cs_arr = cs.split('&')                    //参数字符串分割为数组

          let csobj = {}

          for (let i = 0; i < cs_arr.length; i++) {         //遍历数组，拿到json对象

            csobj[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]

          }


          if(csobj.id==this.chapterPointer.courseId&&csobj.cid==this.chapterPointer.id){
            console.log("进入学习界面")
          }else{
            this.deleteTheChapter();
          }

        }

      })
      this.webViews.addEventListener('load-commit', () => {
        console.log('主页面文档加载')
      })
      this.webViews.addEventListener('page-title-updated', () => {
        console.log('page-title-updated')
      })
      this.webViews.addEventListener('load-commit', () => {
        console.log(' frame文档加载')
      })
      this.webViews.addEventListener('did-frame-finish-load', () => {
        console.log('frame 加载完成')
        console.log('最后一个是主框架frame 加载完成')
      })
      this.webViews.addEventListener('did-finish-load ', () => {
        console.log('最后一个是主框架frame 加载完成')
      })
      this.webViews.addEventListener('page-favicon-updated', () => {
        console.log(' 网页 icon')
      })

      this.webViews.addEventListener('destroyed', () => {
        // console.log(' 网页 destroyed')
      })



      this.webViews.addEventListener('did-stop-loading', () => {
        this.loading=false
        let getURL = this.webViews.getURL() // 访客页面URL
        this.url = getURL
        console.log('页面停止加载', getURL)


        let isDevelopment = process.env.NODE_ENV !== 'production'

        if (isDevelopment) {
          this.webViews.openDevTools()
        }




      })
      // 接受webview页面打印的值
      this.webViews.addEventListener('console-message', (e) => {
        console.log('webview桌面端打印的访客端控制台信息:', e.message)
        if (e.message == '{{【【[[video end]]】】}}') {

          /***
           * 删除在学习的状态
           */
          this.deleteTheChapter();



          /***
           * 之前记录在学习的状态清空
           */
          this.validChildrenLength= {  };
          this.learning= {  };


          /***
           * 从新再来
           */
          this.onhookAction()
          return;
        }

        if (e.message == '{{【【[[learning verification show]]】】}}') {
          this.learningVerificationShow()
          return;
        }

      })
      // 接受webview页面的值
      this.webViews.addEventListener('ipc-message', ({ channel, args }) => {
        console.log(channel, '我是webview传递的值', args)
      })
    },

    open(link) {
      this.$electron.shell.openExternal(link)

    },
    delayer (fun ,time ){
      if (time== undefined) time=500;
      let key=fun+''
      if(!window[key]){
        window[key]={}
      }
      if (window[key].delayer_t!= null){
        clearTimeout(window[key].delayer_t);
        window[key].delayer_t= null ;
      }
      window[key].delayer_t=setTimeout( function (){
        fun.apply(fun);
      },time);
    },
    /***
     * 删除在学习的状态
     */
    deleteTheChapter(){

      if(this.chapterPointer!=null){
        /***
         * 删除在学习的状态
         */
        deleteChapter(this.pid, this.chapterPointer.courseId, this.chapterPointer.id)
        this.chapterPointer=null;
        this.coursePointer=null;
      }
    },


    x(list,i){
      if(i==undefined){
        i=0;
      }
      if(i==list.length){
        console.log(this.allinfo)
        return;
      }
      // this.webViews.executeJavaScript('location.href="http://192.168.11.121:12345/spa/workflow/static4form/index.html?#/main/workflow/req?requestid="'+list[i]+'"&_key=inf3uy"')

      this.info_index=i++;
/*      setTimeout(()=>{
          this.webViews.executeJavaScript(`
              text:document.querySelector('#oTable0').tBodies[0].children[3].cells[15].innerText
        `).then((text) => {
            this.allinfo.push(text);

            setTimeout(()=>{
              console.log(this.allinfo)
                this.x(list,(i))
            },200)
          })
      },6000)*/
    },

    findanswer3(){
      this.info_index++;
      // this.delayer(()=>{
      this.webViews.src='http://192.168.11.121:12345/spa/workflow/static4form/index.html?#/main/workflow/req?requestid='+this.idlist[this.info_index]+'&_key=inf3uy';
      // },1000)
    },
    findanswer2(){


        this.webViews.executeJavaScript(`
            text:document.querySelector('#oTable0').tBodies[0].children[3]==undefined?'':document.querySelector('#oTable0').tBodies[0].children[3].cells[15].innerText
          `).then((text) => {


          if(text==''){
            this.webViews.reload()
          }else{
            // this.allinfo.push(text);
            this.allinfoPush(text)

            console.log(this.allinfo)


          }

          //
        })



    },

    findanswer() {

      this.webViews.executeJavaScript(`
         list:Array.from(document.querySelectorAll('td:nth-child(2)>span.wea-url>a')).map((o)=>{return  parseInt(o.outerHTML.split("flow/req?requestid=")[1].split('\\'')[0])   })
    `).then((list) => {
        console.log('ssss ', list)
        //0: "<a href="javaScript:void(0)" onclick="javaScript:openSPA4Single('/main/workflow/req?requestid=339174',339174,0)">工时填报流程-孔祥润-2023-12-22</a>"

        // this.idlist=list;
        //
        // this.info_index=0;
        // this.webViews.src='http://192.168.11.121:12345/spa/workflow/static4form/index.html?#/main/workflow/req?requestid='+this.idlist[this.info_index]+'&_key=inf3uy';
        //

      });
      return ;

      // let session = this.$electron.remote.session
      // var ses = session.fromPartition('persist:qdjxjy')
      //
      // console.log(ses)
      // console.log(session)
      // session.defaultSession.cookies.get({}, function (error, cookies) {
      //   console.log(cookies)
      // })
      // session.defaultSession.cookies.get({ url : "www.qdjxjy.com.cn" }, function (error, cookies) {
      //   console.log(cookies)
      // })
      //
      // console.log(window.sessionStorage)
      //注入js脚本


      // this.loading = true
      this.answer = []


      this.getLoginInfo().then(() => {

    //     /****
    //      * 判断考试题目url是否准确 并取出id
    //      ***/
    //     let start = this.url.indexOf(this.eUrlIndex)
    //     let end = this.url.indexOf('&eid=')
    //
    //     if (start == -1 && end == -1) {
    //
    //       // this.$electron.remote.dialog.showErrorBox('', '考试界面不匹配')
    //
    //       this.$notify.error({
    //         title: '错误',
    //         message: '考试界面不匹配',
    //         position: 'bottom-right'
    //       })
    //       this.loading = false
    //       return
    //     }
    //
    //     this.deleteTheChapter();
    //
    //     this.eid = this.url.substr(this.eUrlIndex.length, end - this.eUrlIndex.length)
    //
    //     this.webViews.executeJavaScript(`
    //     document.querySelectorAll('input').forEach((item)=>{item.checked=false;console.log(item);item.parentNode.className=item.parentNode.className.replace('is-checked','').replace('is-checked','');   item.parentNode.parentNode.className=item.parentNode.parentNode.className.replace('is-checked','').replace('is-checked',''); item.parentNode.parentNode.removeAttribute('aria-checked'); })
    //     `)
    //
    //
    //     /***
    //      * 获取考题 开始
    //      */
    //     this.webViews.executeJavaScript(`
    //     allWellId:Array.from( document.querySelectorAll('.tab-pane.active>.well>div.media.well')).map((item)=>{return item.id.replace('question','')})
    // `).then((allWellId) => {
    //       console.log('allWellId', allWellId)
    //       this.allIds = allWellId
    //
    //       this.answerRequest()
    //     })
    //     /****
    //      * 获取考题结束
    //      */
      })


    },
    answerRequest() {

      httpAction({
        method: 'POST',
        protocol: 'https:',
        hostname: 'api.qdjxjy.com.cn',
        path: '/zjfore/exam/test/list',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + this.token
        }
      }, '{"courseId":' + this.eid + ',"flag":1,"userid":' + this.userid + '}').then((responseBody) => {
        console.log('responseBody', responseBody)
        if (responseBody.indexOf('502 Bad Gateway') > 0 && responseBody.indexOf('<head><title>') > 0) {
          this.$notify.error({
            title: '错误',
            message: '网站接口数据返回错误，稍后重试',
            position: 'bottom-right'
          })
          return
        }


        let questions = JSON.parse(responseBody)
        console.log('this.allIds this.answer', this.allIds, this.answer)
        console.log('接收到数据：', questions)

        for (let examSubject of questions.examSubjects) {
          if (this.allIds.includes('' + examSubject.id)) {

            let existsCount = this.answer.filter((item) => {
              return item.id == examSubject.id
            })

            if (existsCount == 0) {

              this.webViews.executeJavaScript(`
        _index:document.querySelector('#question` + examSubject.id + `>ul>li>span.badge').innerText
    `).then((_index) => {
                console.log('_index', _index)
                examSubject._index = parseInt(_index)
                this.answer.push(examSubject)


                /****
                 * 自动选择
                 */


                    //
                let answerSplit = examSubject.answer.split('')


                for (let an of answerSplit) {

                  let clickScript = ' if(!document.querySelector(\'#question' + examSubject.id + ' input[value="' + an + '"]\').checked){ document.querySelector(\'#question' + examSubject.id + ' input[value="' + an + '"]\').click();  document.querySelector(\'#question' + examSubject.id + ' input[value="' + an + '"]\').parentNode.className+=\' is-checked\';  document.querySelector(\'#question' + examSubject.id + ' input[value="' + an + '"]\').parentNode.parentNode.className+=\' is-checked\'; }'
                  console.log('clickScript', clickScript)
                  this.webViews.executeJavaScript(clickScript)
                }


              })

            }
            //


          }
        }
        if (this.answer.length < this.allIds.length) {
          setTimeout(() => {
            this.answerRequest()
          }, 200)
        } else {

          // this.$electron.remote.dialog.showMessageBox({
          //   type: 'info',
          //   message: '请检查后交卷!'
          // })

          this.$notify({
            title: '完成',
            message: '请检查后交卷',
            type: 'success',
            position: 'bottom-right'
          })
          this.loading = false
        }
      }).catch((e) => {
        this.$notify.error({
          title: '错误',
          message: '请求异常' + e,
          position: 'bottom-right'
        })
      })

    },

    onhookAction() {
      // this.loading = true
      this.getLoginInfo().then(() => {
        this.courseList = []
        this.courseListLearn = []
        this.queryCourseList(1).then(() => {


          this.queryCourseList(99).then(() => {

            /***
             status == 2  在学习
             status == 4  完成考试
             **/
            this.courseListLearn = this.courseList.filter((item) => {
              return item.status == 2
            })


            /***
             **/
            // this.courseListLearn = this.courseListLearn.map((item) => {
            //   item._status = 0
            //   return item
            // })

            if(this.courseListLearn.length==0){

              this.$alert('暂无需要学习的课程', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.loading = false
                }
              });
              return;
            }

            /***
             * 读取数据库里的正在学习
             */
            queryALl().then((row) => {
              this.learnLog = row
              this.learn()
            })
          })


        })
      })
    },

    /***
     * 获取所有课程
     * @param courseType 类型
     * @returns {Promise<unknown>}
     */
    queryCourseList(courseType) {
      return new Promise((resolve, reject) => {
        this.queryCourseListPage(courseType).then((data) => {
          resolve(data)
          console.log('finish queryCourseListPage ', this.courseList)
        }).catch((e) => {
          reject(e)
        })
      })
    },
    /***
     * 获取所有课程
     * @param courseType 类型
     * @param page 页号
     * @returns {Promise<unknown>}
     */
    queryCourseListPage(courseType, page) {

      let _page = page ? page : 1

      return new Promise((resolve, reject) => {


        let options = {
          method: 'POST',
          protocol: 'https:',
          hostname: 'api.qdjxjy.com.cn',
          path: '/zjfore/course/select/list',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.token
          }
        }
        let body = '{"year":null,"courseType":' + courseType + ',"page":' + _page + ',"pageSize":10,"statusCode":null,"userid":' + this.userid + '}'


        httpAction(options, body).then((responseBody) => {
          console.log('responseBody', responseBody)
          if (responseBody.indexOf('502 Bad Gateway') > 0 && responseBody.indexOf('<head><title>') > 0) {
            this.$notify.error({
              title: '错误',
              message: '网站接口数据返回错误，稍后重试',
              position: 'bottom-right'
            })
            return
          }
          let data = JSON.parse(responseBody)
          console.log('接收到数据：', data)
          if (data.code != 20000) {
            reject(data)
            return
          }
          this.courseList.push.apply(this.courseList, data.courseSelectSet)

          /***
           * 一共多少页
           ***/
          let pageCount = Math.ceil(data.total / 10)

          /***
           * 当前页小于共多少页 继续否则结束
           */
          if (_page < pageCount) {
            this.queryCourseListPage(courseType, _page + 1).then((d) => {
              resolve(this.courseList)
            })
          } else {
            resolve(this.courseList)
            return
          }


        }).catch((e) => {
          reject(this.courseList)
        })


      })


    },
    /***
     * 获取课程章节列表
     * @param courseId 课程id
     * @returns {Promise<unknown>}
     */
    queryCourseChapterList(course) {

      this.chaptersTemp = []
      console.log('course', course)
      return new Promise((resolve, reject) => {
        this.queryCourseChapterListPage(course.courseId).then((data) => {
          resolve(data)
          console.log('finish queryCourseChapterList ', data)
          course.children = JSON.parse(JSON.stringify(this.chaptersTemp))
        }).catch((e) => {
          reject(e)
        })
      })
    }
    ,
    /****
     * 获取章节列表分页
     * @param courseId
     * @param page
     */
    queryCourseChapterListPage(courseId, page) {

      let _page = page ? page : 1

      return new Promise((resolve, reject) => {

        let options = {
          method: 'POST',
          protocol: 'https:',
          hostname: 'api.qdjxjy.com.cn',
          path: '/zjfore/course/chapter/list',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.token
          }
        }

        let body = '{"courseId":' + courseId + ',"page":' + _page + ',"pageSize":100,"agencyId":0,"districtId":0,"industryId":0,"userId":' + this.userid + ',"pickMode":true}'

        httpAction(options, body).then((responseBody) => {

          console.log('responseBody', responseBody)
          if (responseBody.indexOf('502 Bad Gateway') > 0 && responseBody.indexOf('<head><title>') > 0) {
            this.$notify.error({
              title: '错误',
              message: '网站接口数据返回错误，稍后重试',
              position: 'bottom-right'
            })
            return
          }

          let data = JSON.parse(responseBody)
          console.log('接收到数据：', data)

          if (data.code != 20000) {
            reject(data)
            return
          }

          this.chaptersTemp.push.apply(this.chaptersTemp, data.chapters)

          /***
           * 一共多少页
           ***/
          let pageCount = Math.ceil(data.total / 10)

          /***
           * 当前页小于共多少页 继续否则结束
           */
          if (_page < pageCount) {
            this.queryCourseChapterListPage(courseId, _page + 1).then((d) => {
              resolve(this.chaptersTemp)
            })
          } else {
            resolve(this.chaptersTemp)
            return
          }
        }).catch((e) => {
          reject(this.chaptersTemp)
        })


      })

    }
    ,
    learn() {

      console.log('learn')

      if (this.courseListLearn.length == 0) {
        return
      }

      this.coursePointer = null
      this.chapterPointer = null


      for (let courseListLearnElement of this.courseListLearn) {
        /***
         * 状态对在学习的章节数量  小于  状态有效的章节数量
         ***/
        if (courseListLearnElement.status == 2 && (this.learning[courseListLearnElement.courseId] == null || !this.validChildrenLength[courseListLearnElement.courseId] || this.learning[courseListLearnElement.courseId].length < this.validChildrenLength[courseListLearnElement.courseId])) {
          /***
           * 有效的但其他程序正在学习的数量
           * @type {number}
           */
          this.coursePointer = courseListLearnElement
          break
        }
      }
      if(!this.coursePointer){

        this.$alert('没有合适课程 ', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.loading = false
          }
        });
        this.validChildrenLength= {  };
        this.learning= {  };

        return;
      }

      this.queryCourseChapterList(this.coursePointer).then(() => {

        this.$refs.onHookTable.toggleRowExpansion(this.coursePointer)


        /***
         * 状态有效的章节数量
         */
        this.validChildrenLength[this.coursePointer.courseId] = this.coursePointer.children.filter((child) => child.learningStatus == 1 || child.learningStatus == 2).length
        console.log('多开 课程', this.coursePointer.courseId, this.validChildrenLength, this.coursePointer.children)

        for (let child of this.coursePointer.children) {

          console.log('多开 章节', child.id, this.learning[child.courseId])
          /***
           learningStatus == 1 未学习
           learningStatus == 2 学习中
           learningStatus == 3 完成
           */
          if ((child.learningStatus == 1 || child.learningStatus == 2) && (this.learning[child.courseId] == null || this.learning[child.courseId].indexOf(child.id) == -1)) {


            /***
             * 判断是否 在其他端学习
             * @type {*[]}
             */
            let filter = this.learnLog?this.learnLog.filter((item) => item.courseId == child.courseId && item.chapterId == child.id):[]
            console.log('多开 章节其他端 ', filter)

            if (filter.length == 0) {
              this.chapterPointer = child
              break
            } else {
              /***
               * todo 子项不合适 记录 之后判断父项目
               * this.learning[item.courseId].indexOf(child.learning)
               */
              if (!this.learning[child.courseId]) {
                this.learning[child.courseId] = []
              }
              this.learning[child.courseId].push(child.id)

            }
          }
        }
        if (this.coursePointer != null && this.chapterPointer == null) {
          console.log('多开 没有合适章节')

          // this.$alert('没有合适课程或章节', '提示', {
          //   confirmButtonText: '确定',
          //   callback: action => {
          //     this.loading = false
          //   }
          // });
          // this.validChildrenLength= {  };
          // this.learning= {  };

          this.learn()
          return
        }


        if (this.coursePointer != null && this.chapterPointer != null) {

          // ....
          this.url = 'https://www.qdjxjy.com.cn/course/study?id=' + this.chapterPointer.courseId + '&cid=' + this.chapterPointer.id
          if (this.realUrl == this.url) {
            console.log('两个地址相同！')
            // this.refresh()
          } else {
            this.go()

          }

        } else {

          this.$notify({
            title: '完成',
            message: '无可学习课程',
            type: 'success',
            position: 'bottom-right'
          })

          return
        }


      })

    }
    ,

    studyPageLearnHandle() {


      this.videoPlay().then(() => {
        console.log('开始播放')


        insert(this.pid, this.chapterPointer.courseId, this.chapterPointer.id)

        this.videoOnEndedMonitorInit();


        this.observeLearningVerification();




        setTimeout(()=>{

          /***
           * 刷新下状态
           */
          this.queryCourseChapterList(this.coursePointer).then(() => {
          })
        },3000)


      })
    }
    ,

    observeLearningVerification(){

      this.webViews.executeJavaScript(`
              if(window.observeLearningVerificationInterval){
                clearInterval(window.observeLearningVerificationInterval)
                window.observeLearningVerificationInterval=null;
              }
              window.observeLearningVerificationInterval=setInterval(()=>{
                let i=document.querySelector("div[aria-label='学习验证'] > div.el-dialog__body  div > input[placeholder='请输入验证码']");
                if(i){
                  let c=document.querySelector("div[aria-label='学习验证'] > div.el-dialog__body  div > #s-canvas");
                  let d=document.querySelector("div[aria-label='学习验证']")
                  if(c&&d.parentNode.style.display!='none'){
                      console.log('{{【【[[learning verification show]]】】}}')
                  }
                }
              },2000);
          `)
    },
    learningVerificationShow(){
      /***
       * todo 任务栏闪烁
       */
      let win =new remote.getCurrentWindow();
      win.flashFrame(true);
    },
    videoOnEndedMonitorInit() {
      return new Promise((resolve, reject) => {
        console.log('videoOnEndedMonitorInit')
        /***
         * 这种方式容易出问题 用循环保底
         */
        // this.webViews.executeJavaScript(`
        //       document.querySelector('video').onended=()=>{ console.log('{{【【[[video end]]】】}}')}
        //   `)

        this.webViews.executeJavaScript(`
              if(window.observeLearningVideoIsEnd){
                clearInterval(window.observeLearningVideoIsEnd)
                window.observeLearningVideoIsEnd=null;
              }
              window.observeLearningVideoIsEnd=setInterval(()=>{
                if(document.querySelector('video').ended||document.querySelector('video').player.getStatus()=='ended'||document.querySelector('video').player._ended){
                  console.log('{{【【[[video end]]】】}}')

                  clearInterval(window.observeLearningVideoIsEnd)
                  window.observeLearningVideoIsEnd=null;
                }
              },2000);
          `)




      })
    }
    ,
    videoPlay() {

      return new Promise((resolve, reject) => {


        this.webViews.executeJavaScript(`
        isOk:(()=>{
              let _isOk=null;
              let playerButton=document.querySelector('#player-con>.prism-big-play-btn');
              if(playerButton){
                document.querySelector('video').muted=true;
                let messageBox=document.querySelector('.el-message-box__wrapper .el-message-box__message');
                if(messageBox && messageBox.innerText.indexOf('您是否要继续上次的播放?')>=0){
                  document.querySelector('.el-message-box__wrapper .el-message-box__btns .el-button--primary').click();
                  setTimeout(() => {
                    document.querySelector('video').play();
                  }, 1000)
                  console.log('videoPlay 您是否要继续上次的播放? 显示')
                }else{
                  playerButton.click();
                  console.log("videoPlay 播放按钮 找到了 ")
                }
                document.querySelector('video').play();
                _isOk=true;
              }else{
                console.log('videoPlay 播放按钮 没找到')
                _isOk=false;
              }
              return _isOk;
            })()
    `).then((isOk) => {
          console.log('isOk', isOk)
          if (isOk) {
            console.log('videoPlay 播放按钮 找到了 ')
            resolve()
          } else {
            console.log('videoPlay 播放按钮 没找到')
            setTimeout(() => {
              this.videoPlay().then(() => {
                resolve()
              })
            }, 300)
          }
        })


        // let playerButton = document.querySelector('#player-con>.prism-big-play-btn')
        // if (playerButton) {
        //   console.log('videoPlay 播放按钮 找到了 ')
        //   playerButton.click()
        //   resolve()
        // } else {
        //
        //   console.log('videoPlay 播放按钮 没找到')
        //   setTimeout(() => {
        //     this.videoPlay().then(() => {
        //       resolve()
        //     })
        //   }, 300)
        // }
      })

    }
    ,


    getLoginInfo() {
      return new Promise((resolve, reject) => {

        console.log(this.webViews.src)
        /***
         * 取登录信息
         **/
        this.webViews.executeJavaScript(`
         aaa:document.querySelectorAll('td:nth-child(2)>span.wea-url > a')
    `).then((aaa) => {
          console.log('ssss ', aaa)
          // this.sessionStorage = JSON.parse(abc.vuex)
          // this.token = this.sessionStorage.user.token
          // this.userid = this.sessionStorage.user.userid
          // if (!this.token) {
          //   this.$notify.error({
          //     title: '错误',
          //     message: '获取登录状态失败',
          //     position: 'bottom-right'
          //   })
          //   this.loading = false
          //   reject('获取登录状态失败')
          //   return
          // }
          // console.log('获取到tonken', this.token)
          resolve(aaa)
        })

      })
    }
    ,
    go() {
      this.realUrl = this.url
    },
    refresh() {

      this.realUrl = ''
      setTimeout(() => {
        this.realUrl = this.url
      }, 100)
    }
  }
}
</script>


<style scoped>
body {

  -webkit-app-region: drag;
}

#wrapper {
  height: 100%;
  /*padding: 60px 80px;*/
  width: calc(100% - 1px);
  padding: 16px;
}

#logo {
  height: auto;
  margin-bottom: 20px;
  width: 420px;
}

main {
  display: flex;
  justify-content: space-between;
  height: calc(100% - 28px);
  padding: 16px 0px;
}

/*main > div { flex-basis: 50%; }*/

.left-side {
  flex-basis: 78%;
  display: flex;
  flex-direction: column;
}

.right-side {
  padding-left: 16px;
  flex-basis: 22%;
  overflow: auto;
}

.right-side .el-tabs {
  width: 100%;
  height: 100%;
}

.right-side .el-tabs :deep .el-tabs__content {
  height: calc(100% - 40px);
}

.right-side .el-tabs :deep .el-tab-pane {
  height: 100%;
}

.right-side .el-tabs :deep .el-table {
  height: calc(100% - 39px - 16px) !important;
  font-size: 12px;
}

:deep .el-tabs--border-card > .el-tabs__content {
  padding: 5px 2px;
}

.welcome {
  color: #555;
  font-size: 23px;
  margin-bottom: 10px;
}

.title {
  color: #2c3e50;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 6px;
}

.title.alt {
  font-size: 18px;
  margin-bottom: 10px;
}

.doc p {
  color: black;
  margin-bottom: 10px;
}

.doc button {
  font-size: .8em;
  cursor: pointer;
  outline: none;
  padding: 0.75em 2em;
  border-radius: 2em;
  display: inline-block;
  color: #fff;
  background-color: #4fc08d;
  transition: all 0.15s ease;
  box-sizing: border-box;
  border: 1px solid #4fc08d;
}

.doc button.alt {
  color: #42b983;
  background-color: transparent;
}

/deep/ .learning-cell{
  background-color: #8cc5ff;
}
</style>
